<template>
    <div class="container">
        <el-card class="page-container">
            <template #header>
                <div class="header">
                    <span>动物管理</span>
                    <div class="extra">
                        <el-button v-if="shelterId!=null" @click="goBack()" >返回</el-button>
                        <el-button type="primary" @click="visibleDrawer = true; title = '添加动物'; ">添加动物</el-button>
                    </div>
                </div>
            </template>
            <!-- 搜索表单 -->
            <el-form inline>
                <el-form-item label="种类：">
                    <el-select placeholder="请选择" v-model="animalType" style="width: 200px;">
                        <el-option label="猫" value="Cat"></el-option>
                        <el-option label="犬" value="Dog"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="当前状态：">
                    <el-select placeholder="请选择" v-model="animalState" style="width: 200px;">
                        <el-option label="已被收养" value="已被收养"></el-option>
                        <el-option label="未被收养" value="未被收养"></el-option>
                        <el-option label="去世" value="去世"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="animalList">搜索</el-button>
                    <el-button @click="animalType = ''; animalState = ''; animalList()">重置</el-button>
                </el-form-item>
            </el-form>
            <!-- 动物列表 -->
            <el-table :data="animals" style="width: 100%">
                <el-table-column label="序号" type="index"></el-table-column>
                <el-table-column label="动物名称" prop="animalName"></el-table-column>
                <el-table-column label="到收容所的时间/天" prop="animalAge"></el-table-column>
                <el-table-column label="类型" prop="animalType"> </el-table-column>
                <el-table-column label="品种" prop="variety"></el-table-column>
                <el-table-column label="照片" prop="animalPic">
                    <template v-slot="{ row }">
                        <img :src="row.animalPic" style="max-width: 100%; max-height: 100px;">
                    </template>
                </el-table-column>
                <el-table-column label="状态" prop="animalState"></el-table-column>
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-button :icon="Edit" circle plain type="primary" @click="showDrawar(row)"></el-button>
                        <el-button :icon="Delete" circle plain type="danger" @click="deleteAnimal(row)"></el-button>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty description="没有数据" />
                </template>
            </el-table>
            <!-- 分页条 -->
            <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
                layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
                @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
            <!-- 抽屉 -->
            <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
                <!-- 添加动物表单 -->
                <el-form :model="animalModel" label-width="100px" :rules="rules">
                    <el-form-item label="收容所名称" label-width="150px" prop="shelterId">
                        <el-select placeholder="请选择" v-model="animalModel.shelterId">
                            <el-option v-for="s in shelters" :key="s.id" :label="s.shelterName" :value="s.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="动物名称" label-width="150px">
                        <el-input v-model="animalModel.animalName" placeholder="请输入动物名称" minlength="0"
                            maxlength="10"></el-input>
                    </el-form-item>
                    <el-form-item label="到收容所的时间/月" prop="animalAge" label-width="150px">
                        <el-input v-model="animalModel.animalAge" placeholder="请输入在收容所的天数"></el-input>
                    </el-form-item>
                    <el-form-item label="类型" prop="animalType" label-width="150px">
                        <el-select v-model="animalModel.animalType" placeholder="请选择动物的种类">
                            <el-option label="猫" value="Cat" />
                            <el-option label="犬" value="Dog" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="品种" label-width="150px">
                        <el-input v-model="animalModel.variety" placeholder="请输入动物的品种"></el-input>
                    </el-form-item>
                    <el-form-item label="照片" prop="animalPic" label-width="150px">
                        <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                            action="/api/upload" name="file" :headers="{ 'Authorization': tokenStore.token }"
                            :on-success="uploadSuccess">
                            <img v-if="animalModel.animalPic" :src="animalModel.animalPic" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="状态" prop="animalState" label-width="150px">
                        <el-select v-model="animalModel.animalState" placeholder="请选择动物的状态">
                            <el-option label="未被收养" value="未被收养" />
                            <el-option label="已被收养" value="已被收养" />
                            <el-option label="去世" value="去世" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="visibleDrawer = false">取消</el-button>
                        <el-button type="primary" @click="title == '添加动物' ? addAnimal() : updateAnimal()"> 确认
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-drawer>
        </el-card>
    </div>
</template>

<script setup>
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { shelterListService, shelterFindByIdService } from '@/api/shelter'
import { animalListService, animalAddService, animalUpdateService, animalDeleteService } from '@/api/animal.js'
import { useTokenStore } from '@/stores/token.js'
import router from '@/router'

const tokenStore = useTokenStore()

const $route = useRoute()
let shelterId = ref($route.query.shelterId)

const shelters = ref()
const animals = ref()

const animalType = ref()
const animalState = ref()

const pageNum = ref(1)
const total = ref()
const pageSize = ref(3)

const visibleDrawer = ref()

const title = ref()

const animalModel = ref({
    shelterId: 1,
    animalName: '',
    animalAge: 0,
    animalType: '',
    variety: '',
    animalPic: '',
    animalState: ''
})

const onSizeChange = (size) => {
    pageSize.value = size
    animalList()
}

const onCurrentChange = (num) => {
    pageNum.value = num
    animalList()
}

const shelterList = async () => {
    /* 选择下拉框的收容所名称，在后端的可用接口中仅有分页的逻辑，因此
     * 为了显示所有的可选择收容所，将页码以及每页展示的条数进行固定
     */
    let params = {
        pageNum: 1,
        pageSize: 500,
        shelterId: animalModel.shelterId
    }
    let result = await shelterListService(params)
    shelters.value = result.data.items
}

const animalList = async () => {
    let params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        animalType: animalType.value ? animalType.value : null,
        animalState: animalState.value ? animalState.value : null,
        shelterId: shelterId.value ? shelterId.value : null
    }
    let result = await animalListService(params)
    total.value = result.data.total
    animals.value = result.data.items
}

const uploadSuccess = (result) => {
    console.log(result);
    animalModel.value.animalPic = result.data;
}

const checkAnimalAge = (rule, value, callback) => {
    const reg = /^(0|[1-9]\d*)$/;
    if (reg.test(value)) {
        callback();
    } else {
        callback(new Error('请输入大于等于0的整数'));
    }
}

const rules = {
    animalType: [
        { required: true, message: '请选择动物种类', trigger: 'blur' }
    ],
    animalPic: [
        { required: true, message: '请添加照片', trigger: 'blur' }
    ],
    animalAge: [
        { validator: checkAnimalAge, trigger: 'blur' }
    ],
    animalState: [
        { required: true, message: '请添加动物状态', trigger: 'blur' }
    ],
    shelterId: [
        { required: true, message: '请添加收容所名称', trigger: 'blur' }
    ]
}

const addAnimal = async () => {
    let result = await animalAddService(animalModel.value)
    ElMessage.success('添加成功')
    animalList()
    visibleDrawer.value = false
}

const updateAnimal = async () => {
    let result = await animalUpdateService(animalModel.value);
    ElMessage.success('修改成功')
    animalList()
    visibleDrawer.value = false
}

const showDrawar = (row) => {
    visibleDrawer.value = true;
    title.value = '编辑动物';
    animalModel.value.shelterId = row.shelterId;
    animalModel.value.animalName = row.animalName;
    animalModel.value.animalAge = row.animalAge;
    animalModel.value.animalType = row.animalType;
    animalModel.value.variety = row.variety;
    animalModel.value.animalPic = row.animalPic;
    animalModel.value.animalState = row.animalState;
    animalModel.value.id = row.id
}

const deleteAnimal = (row) => {
    ElMessageBox.confirm(
        '你确认要删除该动物吗?',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        let result = await animalDeleteService(row.id);
        ElMessage({
            type: 'success',
            message: '删除成功',
        })
        animalList()
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '用户取消了删除',
        })
    })
}

const goBack = ()=>{
    router.go(-1);
}

shelterList();
animalList();
</script>

<style lang="scss" scoped>
.container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    .page-container {
        width: 95%;
        height: 88vh;
        background-color: #e0f3f8;

        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
    }

    .avatar-uploader {
        :deep() {
            .avatar {
                width: 178px;
                height: 178px;
                display: block;
            }

            .el-upload {
                border: 1px dashed var(--el-border-color);
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
                transition: var(--el-transition-duration-fast);
            }

            .el-upload:hover {
                border-color: var(--el-color-primary);
            }

            .el-icon.avatar-uploader-icon {
                font-size: 28px;
                color: #8c939d;
                width: 178px;
                height: 178px;
                text-align: center;
            }
        }
    }

    .editor {
        width: 100%;

        :deep(.ql-editor) {
            min-height: 200px;
        }
    }
}
</style>